package com.spit.tph.nike_mvp.presenter

import CONSUMABLES_RECEIVE
import CONSUMABLES_RESTOCK
import CONSUMABLES_WAREHOUSE
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v4.app.FragmentActivity
import android.support.v7.widget.AppCompatButton
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import com.csl.ams.nike_mvp.BasePresenter
import com.csl.ams.nike_mvp.bean.BaseResponseBean
import com.csl.ams.nike_mvp.bean.WheelchairUploadBean
import com.google.gson.Gson
import com.google.zxing.integration.android.IntentIntegrator
import com.orhanobut.hawk.Hawk
import com.spit.tph.CaptureActivityPortrait
import com.spit.tph.Event.DialogEvent
import com.spit.tph.InternalStorage
import com.spit.tph.MainActivity
import com.spit.tph.R
import com.spit.tph.WebService.RetrofitClient
import com.spit.tph.nike_mvp.impl.ConsumablesContract
import com.spit.tph.nike_mvp.ui.ConsumablesDescFrg
import com.spit.tph.nike_mvp.utils.ToastUtil
import com.yyc.stocktake.bean.DataBean
import org.greenrobot.eventbus.EventBus
import org.json.JSONArray
import org.json.JSONObject
import retrofit2.Call

import retrofit2.Callback

import retrofit2.Response
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Collections


/**
 * User: Nike
 *  2024/2/23 17:27
 */
class ConsumablesPresenter : BasePresenter<ConsumablesContract.View>(), ConsumablesContract.Presenter {

    val companyId = Hawk.get(InternalStorage.Setting.COMPANY_ID, "")
    val userid = Hawk.get(InternalStorage.OFFLINE_CACHE.USER_ID, "")

    override fun onListRequest() {
        RetrofitClient.getSPGetWebService().getConsumablesList(companyId, userid)
            .enqueue(object : Callback<BaseResponseBean<List<DataBean>>> {
                @RequiresApi(Build.VERSION_CODES.N)
                override fun onResponse(
                    call: Call<BaseResponseBean<List<DataBean>>>,
                    response: Response<BaseResponseBean<List<DataBean>>>
                ) {
                    val body = response.body()
                    if (body?.code == 200){
                        val data = body.data
                        if (data != null && data.size != 0){
//                            (data as ArrayList<DataBean>).sortWith(compareBy({ it.currentInventory }, { it.id }))
                            /*var list = Comparator
                                .comparing(DataBean::currentInventory)
                                .thenComparing(DataBean::id);
                            Collections.sort(data, list);*/

                            val (list1, list2) = data.partition { it.currentInventory != 0 }
                            Collections.reverse(list1)
                            var list = ArrayList<DataBean>()
                            list.addAll(list1)
                            list.addAll(list2)




                            mRootView?.setListCallback(list as java.util.ArrayList<DataBean>)
                        }
                    }else{
                        ToastUtil.showShortToast(body?.msg)
                        mRootView?.setNoData()
                    }
                }

                override fun onFailure(call: Call<BaseResponseBean<List<DataBean>>>, t: Throwable) {
                    Log.e("ConsumablesPresenter", t.toString())
                }
            })
    }

    override fun onMedicalTeamList() {
        RetrofitClient.getSPGetWebService().medicalTeamList(companyId, userid)
            .enqueue(object : Callback<BaseResponseBean<List<DataBean>>> {
                override fun onResponse(
                    call: Call<BaseResponseBean<List<DataBean>>>,
                    response: Response<BaseResponseBean<List<DataBean>>>
                ) {
                    val body = response.body()
                    if (body?.code == 200){
                        val data = body.data
                        if (data != null && data.size != 0){
                            mRootView?.setMedicalTeamListCallback(data as ArrayList<DataBean>)
                        }
                    }
                }

                override fun onFailure(call: Call<BaseResponseBean<List<DataBean>>>, t: Throwable) {
                    Log.e("ConsumablesPresenter", t.toString())
                }
            })
    }

    override fun toZking(activity: FragmentActivity?) {
        IntentIntegrator(activity)
            .setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)
            .setPrompt("")
            .setCameraId(0)
            .setBeepEnabled(true)
            .setBarcodeImageEnabled(true)
            .setCaptureActivity(CaptureActivityPortrait::class.java)
            .initiateScan()
    }

    override fun onUploaded(
        bean: DataBean?,
        teamId: String?,
        listBean1: ArrayList<DataBean>,
        mCStatus: Int,
        requireActivity: FragmentActivity,
        restockBean: DataBean?
    ) {
        var listBean = ArrayList<DataBean>()
        listBean.addAll(listBean1)

        val noList = ArrayList<DataBean>()

        val jsonArray = JSONArray()
        listBean.forEachIndexed { index, dataBean ->
            val obj = JSONObject()
            obj.put("rono", dataBean.rono)
            obj.put("changeFlag", mCStatus)
            obj.put("changeQuantity", dataBean.num)
            obj.put("changeDate", getCurrentTimeString())
            obj.put("changeRemarks", dataBean.remark)
            //病人编号
            if (teamId != null){
                obj.put("patientId", teamId)
            }
            //领用
            if (mCStatus == CONSUMABLES_RECEIVE){
                obj.put("changeMethod", 0)
                //团队
                obj.put("mtRoNo", bean?.rono)
                //物资点
                obj.put("changeLocation", restockBean?.rono)
            }else if (mCStatus == CONSUMABLES_WAREHOUSE){//入库
                obj.put("changeMethod", 1)
                obj.put("changeLocation", bean?.rono)
            }else if (mCStatus == CONSUMABLES_RESTOCK){//铺货
                obj.put("changeMethod", 1)
                obj.put("changeLocation", bean?.rono)
                obj.put("mLocation", restockBean?.rono)
            }
            jsonArray.put(obj)
        }
        val obj = JSONObject()
        obj.put("consumables", jsonArray)
        Log.e("", obj.toString())

//        val sb = StringBuffer()
//        noList.joinTo(sb, separator = ",") { it.consumablesNo }
//        Log.e("不符合", sb.toString())
//
//        val sb1 = StringBuffer()
//        listBean.joinTo(sb1, separator = ",") { it.consumablesNo }
//        Log.e("符合", sb1.toString())

        RetrofitClient.getSPGetWebService().ConsumableInventoryChangesUploaded(companyId, userid, obj.toString())
            .enqueue(object : Callback<WheelchairUploadBean> {
                override fun onResponse(
                    call: Call<WheelchairUploadBean>,
                    response: Response<WheelchairUploadBean>
                ) {
                    val body = response.body()
                    body?.data?.let { Log.e("", it) }
                    if (body?.code == 200){
                        EventBus.getDefault().post(
                            DialogEvent(
                                requireActivity.getString(R.string.app_name),
                                requireActivity.getString(R.string.upload_successful),
                                true,
                                noList,
                                listBean)
                        )
                        /*if (noList.size == 0){
                            EventBus.getDefault().post(
                                DialogEvent(
                                    requireActivity.getString(R.string.app_name),
                                    requireActivity.getString(R.string.upload_successful),
                                    true,
                                    noList,
                                    listBean)
                            )
                        }else{
                            val sb = StringBuffer()
                            noList.joinTo(sb, separator = ",") { it.consumablesNo }
                            EventBus.getDefault().post(
                                DialogEvent(
                                    requireActivity.getString(R.string.app_name),
                                    requireActivity.getString(R.string.upload_successful) + "\n" + sb.toString() + requireActivity.getString(R.string.text18),
                                    true,
                                    noList,
                                    listBean
                                )
                            )
                        }*/

                    }else{
                        val data = body?.data
                        if (data!!.isNotEmpty()){
                            var sb = StringBuffer()
                            val noList = listBean.filter { it.rono in data.split(",") }.also {
                                sb.append(it.joinToString(",") { it.consumablesNo })
                            }
                            EventBus.getDefault().post(
                                DialogEvent(
                                    requireActivity.getString(R.string.app_name),
                                    requireActivity.getString(R.string.text17) + sb.toString() + requireActivity.getString(R.string.text19),
                                    true,
                                    noList,
                                    noList
                                )
                            )
                        }
                    }
                }

                override fun onFailure(call: Call<WheelchairUploadBean>, t: Throwable) {
                    Log.e("ConsumablesPresenter", t.toString())
                }
            })

    }

    //隐藏弹窗，显示提交
    override fun toUploadedUi(mLayout: LinearLayout?, mBtConfirm: AppCompatButton?) {
        mLayout?.visibility = View.GONE
        mBtConfirm?.visibility = View.VISIBLE
    }

    override fun onAsk(mCStatus: Int) {
        when(mCStatus) {
            //领用
            CONSUMABLES_RECEIVE -> {
                onMedicalTeamList()
                onMaterialList()
                onTherapist()
            }
            //入库
            CONSUMABLES_WAREHOUSE ->{
                onWarehouseList()
            }
            //补货
            CONSUMABLES_RESTOCK ->{
                onWarehouseList()
                onMaterialList()
            }
        }
    }

    override fun onWarehouseList() {
        RetrofitClient.getSPGetWebService().warehouseList(companyId, userid)
            .enqueue(object : Callback<BaseResponseBean<List<DataBean>>> {
                override fun onResponse(
                    call: Call<BaseResponseBean<List<DataBean>>>,
                    response: Response<BaseResponseBean<List<DataBean>>>
                ) {
                    val body = response.body()
                    if (body?.code == 200){
                        val data = body.data
                        if (data != null && data.size != 0){
                            mRootView?.setWarehouseListCallback(data as ArrayList<DataBean>)
                        }
                    }
                }

                override fun onFailure(call: Call<BaseResponseBean<List<DataBean>>>, t: Throwable) {
                    Log.e("ConsumablesPresenter", t.toString())
                }
            })
    }

    override fun onMaterialList() {
        RetrofitClient.getSPGetWebService().materialPointsList(companyId, userid)
            .enqueue(object : Callback<BaseResponseBean<List<DataBean>>> {
                override fun onResponse(
                    call: Call<BaseResponseBean<List<DataBean>>>,
                    response: Response<BaseResponseBean<List<DataBean>>>
                ) {
                    val body = response.body()
                    if (body?.code == 200){
                        val data = body.data
                        if (data != null && data.size != 0){
                            mRootView?.setMaterialListCallback(data as ArrayList<DataBean>)
                        }
                    }
                }

                override fun onFailure(call: Call<BaseResponseBean<List<DataBean>>>, t: Throwable) {
                    Log.e("ConsumablesPresenter", t.toString())
                }
            })
    }

    override fun onUploaded2(
        requireActivity: FragmentActivity,
        json: String,
        listBean: ArrayList<DataBean>
    ) {
        Log.e("", json)
        Log.e("companyId", companyId)
        Log.e("userid", userid)

        RetrofitClient.getSPGetWebService().ConsumableInventoryChangesUploaded(companyId, userid, json)
            .enqueue(object : Callback<WheelchairUploadBean> {
                override fun onResponse(
                    call: Call<WheelchairUploadBean>,
                    response: Response<WheelchairUploadBean>
                ) {
                    val body = response.body()
                    if (body?.code == 200){
                        EventBus.getDefault().post(
                            DialogEvent(
                                requireActivity.getString(R.string.app_name),
                                requireActivity.getString(R.string.upload_successful),
                                true)
                        )

                    }else{
                        val data = body?.data
                        if (data!!.isNotEmpty()){
                            var sb = StringBuffer()
                            val noList = listBean.filter { it.rono in data.split(",") }.also {
                                sb.append(it.joinToString(",") { it.consumablesNo })
                            }
                            EventBus.getDefault().post(
                                DialogEvent(
                                    requireActivity.getString(R.string.app_name),
                                    requireActivity.getString(R.string.text17) + sb.toString() + requireActivity.getString(R.string.text19),
                                    true,
                                    noList,
                                    noList
                                )
                            )
                        }
                    }
                }

                override fun onFailure(call: Call<WheelchairUploadBean>, t: Throwable) {
                    Log.e("ConsumablesPresenter", t.toString())
                }
            })

    }

    override fun onTherapist() {
        RetrofitClient.getSPGetWebService().getTherapists(companyId, userid)
            .enqueue(object : Callback<BaseResponseBean<List<DataBean>>> {
                override fun onResponse(
                    call: Call<BaseResponseBean<List<DataBean>>>,
                    response: Response<BaseResponseBean<List<DataBean>>>
                ) {
                    val body = response.body()
                    if (body?.code == 200){
                        val data = body.data
                        if (data != null && data.size != 0){
                            mRootView?.setTherapistsListCallback(data as ArrayList<DataBean>)
                        }
                    }
                }

                override fun onFailure(call: Call<BaseResponseBean<List<DataBean>>>, t: Throwable) {
                    Log.e("ConsumablesPresenter", t.toString())
                }
            })
    }

    fun toConsumablesDescFrg(list: ArrayList<DataBean>, activity: FragmentActivity?, mCStatus: Int) {
        if (list.any { it.currentInventory == 0 } && mCStatus != CONSUMABLES_WAREHOUSE){
            ToastUtil.showShortToast(activity?.getString(R.string.text10))
            return
        }
        val frg = ConsumablesDescFrg()
        val bundle = Bundle()
        bundle.putInt("status", mCStatus)
        bundle.putString("list", Gson().toJson(list))
        frg.setArguments(bundle);
        (activity as MainActivity).replaceFragment(frg)
    }

    fun getCurrentTimeString(): String {
        val calendar = Calendar.getInstance()
        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        return dateFormat.format(calendar.time)
    }
}